// 导入必要的模块
const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const { sequelize, createDatabase } = require('./config/database');

// 导入路由模块
const residentRoutes = require('./routes/residentRoutes');
const healthRecordRoutes = require('./routes/healthRecordRoutes');

// 创建 Express 应用实例
const app = express();

// 中间件配置
app.use(cors({
    origin: '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(express.json());
app.use(morgan('dev'));

// 初始化数据库
async function initializeDatabase() {
    try {
        // 测试数据库连接
        await sequelize.authenticate();
        console.log('数据库连接测试成功');
        
        await createDatabase();
        await sequelize.sync();
        console.log('数据库同步成功');
    } catch (err) {
        console.error('数据库初始化失败:', err);
        process.exit(1);
    }
}

// 路由配置
app.use('/api', residentRoutes);
app.use('/api', healthRecordRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({
        success: false,
        message: '服务器内部错误'
    });
});

// 启动应用
async function startServer(port) {
    try {
        console.log('正在初始化数据库...');
        await initializeDatabase();
        
        const server = app.listen(port, () => {
            console.log(`服务器运行在端口 ${port}`);
        });

        server.on('error', (err) => {
            if (err.code === 'EADDRINUSE') {
                console.log(`端口 ${port} 已被占用，尝试使用端口 ${port + 1}`);
                server.close();
                startServer(port + 1);
            } else {
                console.error('服务器错误:', err);
                process.exit(1);
            }
        });
    } catch (err) {
        console.error('服务器启动失败:', err);
        process.exit(1);
    }
}

// 启动服务器
startServer(3000);

module.exports = app;